import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:joyagoo/pages/widget/joy_product_card_widget.dart';
import 'package:joyagoo/utils/route_utils.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:async';
import 'dart:io';
import '../config/app_colors.dart';
import '../config/app_theme.dart';
import '../config/app_url_address.dart';
import '../model/productListModel.dart';
import '../utils/LitDialogUtil.dart';
import '../utils/LitplatformVoListWidget.dart';
import '../utils/JoyActionService.dart';
import '../utils/JoyBlocUtil.dart';
import '../utils/JoyCacheManager.dart';
import '../utils/RecordBrowseManager.dart';
import '../utils/currency_manager.dart';
import 'JoyWebViewManager.dart';
import 'joy_home_bloc.dart';
import 'joy_login_page.dart';
import 'widget/image_carousel_widget.dart';

class PlatformVoList {
  final String? inviteCode;
  final String? logoImage;
  final String? name;
  final String? nameEn;
  final String? platformDesc;
  final String? productLink;
  final int? recommendFlag;
  final int? sort;
  final String? showFlag;
  final String? recommendLogo;
  PlatformVoList({
    this.inviteCode,
    this.logoImage,
    this.name,
    this.nameEn,
    this.platformDesc,
    this.productLink,
    this.recommendFlag,
    this.sort,
    this.showFlag,
    this.recommendLogo,
  });
  factory PlatformVoList.fromJson(Map<String, dynamic> json) =>
      _$PlatformVoListFromJson(json);
  Map<String, dynamic> toJson() => _$PlatformVoListToJson(this);
}

PlatformVoList _$PlatformVoListFromJson(Map<String, dynamic> json) =>
    PlatformVoList(
      inviteCode: json['inviteCode'] as String?,
      logoImage: json['logoImage'] as String?,
      name: json['name'] as String?,
      nameEn: json['nameEn'] as String?,
      platformDesc: json['platformDesc'] as String?,
      productLink: json['productLink'] as String?,
      recommendFlag: (json['recommendFlag'] as num?)?.toInt(),
      sort: (json['sort'] as num?)?.toInt(),
      showFlag: json['showFlag'] as String?,
      recommendLogo: json['recommendLogo'] as String?,

    );



Map<String, dynamic> _$PlatformVoListToJson(PlatformVoList instance) =>
    <String, dynamic>{
      'inviteCode': instance.inviteCode,
      'logoImage': instance.logoImage,
      'name': instance.name,
      'nameEn': instance.nameEn,
      'platformDesc': instance.platformDesc,
      'productLink': instance.productLink,
      'recommendFlag': instance.recommendFlag,
      'sort': instance.sort,
      'showFlag': instance.showFlag,
      'recommendLogo': instance.recommendLogo,
    };

class JoyProductDetailPage extends StatefulWidget {
  final String itemNo;
  final String channel;
  final String productName;

  const JoyProductDetailPage({Key? key, required this.itemNo,required this.channel,required this.productName}) : super(key: key);


  @override
  State<StatefulWidget> createState() {
    return JoyProductDetailPageState();
  }
}

class JoyProductDetailPageState extends State<JoyProductDetailPage>
    with TickerProviderStateMixin {
  PageController _pageController = PageController();
  PageController _carouselPageController = PageController();
  Timer? _autoScrollTimer;
  int _currentImageIndex = 0;
  int _currentCarouselPage = 0;
  DraggableScrollableController _draggableController = DraggableScrollableController();
  
  // 示例数据
  List<String> _productImages = [
  ];
  
  String _productPrice = "\$ 189.90";
  String _originalPrice = "\$ 249.90";
  String _brand = "CHOICE";
  List<String> _sizes = ["S", "M", "L", "XL"];
  String _selectedSize = "S";
  List<Color> _colors = [
    Colors.black,
    Color(0xFF87CEEB),
    Color(0xFFFFB6C1),
  ];
  Color _selectedColor = Colors.black;
  int _quantity = 1;

  late JoyHomeBloc homeBloc;

  String error_alc = "No Data";
  bool isNetError_alc = false;
  String errorImage_alc = "";

  // 网络状态相关
  bool _isNetworkAvailable = true;
  int _retryCount = 0;
  final int _maxRetryCount = 3;
  Timer? _networkCheckTimer;

  String title = "";
  String price = "0.00";
  /// 折扣价格
  String discountPrice = "0.00";


  double discountRate = 0.00;

  int isCollection = 0;

  // 是否是折扣状态 有折扣 则显示倒计时 折扣价格
  int statusRate = 0;

  bool _isInSpecialDateRange() {
    final now = DateTime.now();
    final specialStartDate = DateTime(2025, 10, 27);
    final specialEndDate = DateTime(2025, 10, 29, 23, 59, 59);
    
    // 🔥 调试日志
    // debugPrint("=== 日期判断调试 ===");
    // debugPrint("当前时间: ${now.toString()}");
    // debugPrint("特殊日期开始: ${specialStartDate.toString()}");
    // debugPrint("特殊日期结束: ${specialEndDate.toString()}");
    
    final isInRange = now.isAfter(specialStartDate.subtract(Duration(days: 1))) && 
                     now.isBefore(specialEndDate.add(Duration(days: 1)));
    //
    // debugPrint("是否在特殊日期范围内: $isInRange");
    // debugPrint("=== 日期判断结束 ===");
    
    return isInRange;
  }
  List<dynamic> imageList = [];
  List<dynamic> imageMaxList = [];
  List<dynamic> imageMinList = [];
  List<dynamic> platformList = []; // 添加平台列表数据
  String sku = "";
  String productLink = "";
  String channelFrom = "";


  String currentTime = "";
  String beginTime = "";
  String endTime = "";
  
  // 倒计时相关
  Timer? _countdownTimer;
  int _remainingSeconds = 0;
  int _remainingMinutes = 0;
  int _remainingHours = 0;


  List SimilarityList = [];
  
  // 🔥 用于监听UserAppTheme变化的计数器
  int _appThemeUpdateCounter = 0;

  @override
  void initState() {
    super.initState();
    _startAutoScroll();
    _checkNetworkConnection(); // 初始化时检查网络状态
    _startNetworkMonitoring(); // 启动网络状态监控
    _loadAppThemeState(); // 
  }
  
  // 🔥 主动获取UserAppTheme状态
  Future<void> _loadAppThemeState() async {
    try {
      await JoyActionService.LitVersionInfo(context, showUpdateDialog: false);
      debugPrint("✅ UserAppTheme状态已更新: ${AppTheme.UserAppTheme}");
      
      // 🔥 更新计数器以触发UI刷新
      if (mounted) {
        setState(() {
          _appThemeUpdateCounter++;
        });
        debugPrint("🔄 UI已刷新，按钮布局已更新");
      }
    } catch (e) {
      debugPrint("❌ 获取UserAppTheme状态失败: $e");
      debugPrint("使用默认值: ${AppTheme.UserAppTheme}");
    }
  }

  // 检查用户登录状态
  Future<bool> _checkLoginStatus() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getBool('isLoggedIn') ?? false;
  }

  // 显示登录提示对话框
  void _showLoginRequiredDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: const Color(0xFFFAF9F7), // 米白色背景
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16.r),
        ),
        title: Row(
          children: [
            Icon(
              Icons.login,
              color: const Color(0xFFFF6B35),
              size: 24.sp,
            ),
            SizedBox(width: 8.w),
            Text(
              'Login Required',
              style: TextStyle(
                fontSize: 18.sp,
                fontWeight: FontWeight.w600,
                color: const Color(0xFFFF6B35),
              ),
            ),
          ],
        ),
        content: Text(
          'Please log in to add items to your favorites. You can access all your saved items after logging in.',
          style: TextStyle(
            fontSize: 14.sp,
            color: Colors.black,
            height: 1.4,
          ),
        ),
        actions: [
          Center(
            child: ElevatedButton(
              onPressed: () => Navigator.pop(context),
              style: ElevatedButton.styleFrom(
                backgroundColor: const Color(0xFFFF6B35),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8.r),
                ),
                elevation: 0,
                padding: EdgeInsets.symmetric(horizontal: 32.w, vertical: 12.h),
              ),
              child: Text(
                'I understand',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
  
  @override
  void dispose() {
    _autoScrollTimer?.cancel();
    _networkCheckTimer?.cancel();
    _countdownTimer?.cancel();
    _pageController.dispose();
    _carouselPageController.dispose();
    _draggableController.dispose();
    super.dispose();
  }
  
  void _startAutoScroll() {
    _autoScrollTimer = Timer.periodic(Duration(seconds: 3), (timer) {
      if (_pageController.hasClients) {
        int nextPage = (_currentImageIndex + 1) % imageList.length;
        _pageController.animateToPage(
          nextPage,
          duration: Duration(milliseconds: 300),
          curve: Curves.easeInOut,
        );
      }
    });
  }
  
  void _stopAutoScroll() {
    _autoScrollTimer?.cancel();
  }
  
  void _resumeAutoScroll() {
    _stopAutoScroll();
    _startAutoScroll();
  }

  // 启动网络状态监控
  void _startNetworkMonitoring() {
    _networkCheckTimer = Timer.periodic(Duration(seconds: 5), (timer) {
      _checkNetworkConnection();
    });
  }

  // 检查网络连接状态
  Future<bool> _checkNetworkConnection() async {
    try {
      final result = await InternetAddress.lookup('google.com');
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
        bool wasUnavailable = !_isNetworkAvailable;
        setState(() {
          _isNetworkAvailable = true;
        });
        
        // 如果网络从不可用变为可用，显示恢复提示
        if (wasUnavailable) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Row(
                children: [
                  Icon(Icons.wifi, color: Colors.white, size: 16),
                  SizedBox(width: 8),
                  Text('Network connection restored'),
                ],
              ),
              backgroundColor: Colors.green,
              duration: Duration(seconds: 2), 
            ),
          );
        }
        return true;
      }
    } catch (_) {
      setState(() {
        _isNetworkAvailable = false;
      });
    }
    return false;
  }

  // 启动倒计时
  void _startCountdown() {
    _countdownTimer?.cancel(); // 取消之前的计时器
    
    if (statusRate == 1 && endTime.isNotEmpty && currentTime.isNotEmpty) {
      _calculateRemainingTime();
      
      // 每秒更新一次倒计时
      _countdownTimer = Timer.periodic(Duration(seconds: 1), (timer) {
        if (_remainingSeconds > 0 || _remainingMinutes > 0 || _remainingHours > 0) {
          _updateCountdown();
        } else {
          // 倒计时结束，停止计时器
          timer.cancel();
          setState(() {
            statusRate = 0; // 活动结束，自动切换到显示原价
          });
        }
      });
    }
  }

  // 计算剩余时间
  void _calculateRemainingTime() {
    try {
      // 解析时间字符串 (假设格式为 "2024-01-01 12:00:00")
      DateTime current = DateTime.parse(currentTime);
      DateTime end = DateTime.parse(endTime);
      
      Duration difference = end.difference(current);
      int totalSeconds = difference.inSeconds;
      
      if (totalSeconds > 0) {
        _remainingHours = totalSeconds ~/ 3600;
        _remainingMinutes = (totalSeconds % 3600) ~/ 60;
        _remainingSeconds = totalSeconds % 60;
      } else {
        // 活动已结束
        _remainingHours = 0;
        _remainingMinutes = 0;
        _remainingSeconds = 0;
        statusRate = 0;
      }
    } catch (e) {
      debugPrint("时间解析错误: $e");
      _remainingHours = 0;
      _remainingMinutes = 0;
      _remainingSeconds = 0;
    }
  }

  // 更新倒计时
  void _updateCountdown() {
    setState(() {
      if (_remainingSeconds > 0) {
        _remainingSeconds--;
      } else if (_remainingMinutes > 0) {
        _remainingMinutes--;
        _remainingSeconds = 59;
      } else if (_remainingHours > 0) {
        _remainingHours--;
        _remainingMinutes = 59;
        _remainingSeconds = 59;
      }
    });
  }

  // 智能重试机制
  Future<void> _retryImageLoad() async {
    if (_retryCount < _maxRetryCount) {
      _retryCount++;
      
      // 显示重试提示
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Row(
            children: [
              SizedBox(
                width: 16,
                height: 16,
                child: CircularProgressIndicator(
                  strokeWidth: 2,
                  valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                ),
              ),
              SizedBox(width: 12),
              Text('Retrying to load images... (${_retryCount}/${_maxRetryCount})'),
            ],
          ),
          backgroundColor: Colors.orange,
          duration: Duration(seconds: 2),
        ),
      );
      
      // 检查网络连接
      bool isConnected = await _checkNetworkConnection();
      if (isConnected) {
        // 清除缓存并重新加载
        await JoyCacheManager.instance.emptyCache();
        setState(() {
          // 触发重新构建，重新加载图片
        });
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('Network unavailable, please check settings'),
            backgroundColor: Colors.red,
            duration: Duration(seconds: 3),
          ),
        );
      }
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('Maximum retry attempts reached, please try later'),
          backgroundColor: Colors.red,
          duration: Duration(seconds: 3),
        ),
      );
    }
  }

  void reloadData(){
    // if (Platform.isIOS) {
    //   // // 预热WebView，提高首次加载速度  只有iOS 预热加载  安卓正常加载 即可
    //   final webViewManager = JoyWebViewManager();
    //   webViewManager.preloadWebView();
    // } else if (Platform.isAndroid) {

    // }
    homeBloc.add(GetJOYProductDetailEvent(context,widget.channel,widget.itemNo,appDetailType));

  }

  @override
  Widget build(BuildContext context) {
    return mainBloc();
  }

  Widget mainBloc(){
    return JoyBlocUtil.getAppNoBarBloc(builder: (context, state) {
      return Stack(
        children: [
          detailMain(),
        ],
      );
    }, create: (_) {
      homeBloc = JoyHomeBloc();
      reloadData();
      return homeBloc;
    }, buildWhen: (previousState, state) {
      if(state is GetJOYProductDetailEventSuccess){
        isNetError_alc = false;
        debugPrint("state = ${state.data}");
        Map productDetail = state.data??{};
        title = productDetail["title"]??"";
        price = "${productDetail["price"]??0.00}";
        discountPrice = "${productDetail["discountPrice"]??0.00}";

        imageList = productDetail["imageList"]??[];
        sku = "${productDetail["skuNumber"]??0}";
        channelFrom = productDetail["channel"]??"";
        discountRate = productDetail["discountRate"]??0.00;
        statusRate = productDetail["status"]??0;
        currentTime = productDetail["currentTime"]??"";
        beginTime = productDetail["beginTime"]??"";
        endTime = productDetail["endTime"]??"";
        
        // 启动倒计时逻辑
        _startCountdown();

        List platformVoList = productDetail["platformVoList"]??[];
        platformList = platformVoList; // 保存平台列表数据

        if(platformVoList.isNotEmpty){
          // 查找平台对应的productLink，优先级：LitBuy > iTaobuy > 其他
          String? litbuyLink;
          String? itaobuyLink;
          String? fallbackLink;

          for(Map platform in platformVoList) {
            String platformName = platform["nameEn"] ?? "";
            String platformLink = platform["productLink"] ?? "";

            // 记录第一个有效链接作为备选
            if(fallbackLink == null && platformLink.isNotEmpty) {
              fallbackLink = platformLink;
            }

            String lowerPlatformName = platformName.toLowerCase();
            
            // 优先查找LitBuy相关平台
            if((lowerPlatformName.contains("litbuy")) && platformLink.isNotEmpty) {
              litbuyLink = platformLink;
              debugPrint("🔍 匹配到LitBuy平台: '$platformName' -> 链接: $platformLink");
              break; // 找到LitBuy就直接使用，不再继续查找
            }
            
            // 其次查找iTao相关平台（只在没找到LitBuy时才记录）
            if(litbuyLink == null && (lowerPlatformName.contains("itao")) && platformLink.isNotEmpty) {
              itaobuyLink = platformLink;
              debugPrint("🔍 匹配到iTao平台: '$platformName' -> 链接: $platformLink");
            }
          }

          // 按优先级选择链接：LitBuy > iTaobuy > 其他备选链接
          if(litbuyLink != null) {
            productLink = litbuyLink;
            debugPrint("✅ 最优选择 - 使用LitBuy平台链接: $productLink");
          } else if(itaobuyLink != null) {
            productLink = itaobuyLink;
            debugPrint("✅ 次优选择 - 使用iTaobuy平台链接: $productLink");
          } else if(fallbackLink != null) {
            productLink = fallbackLink;
            debugPrint("⚠️ 备选方案 - 使用其他平台链接: $productLink");
          } else {
            productLink = "${productDetail["sourceUrl"]??""}";
            debugPrint("❌ 未找到任何平台链接，使用sourceUrl: $productLink");
          }
        }else{
          productLink = "${productDetail["sourceUrl"]??""}";
          debugPrint("📝 平台列表为空，使用sourceUrl: $productLink");
        }

        String mainUrl = productDetail["mainImage"]??"";


        // imageMaxList 最多显示6张图
        imageMaxList = imageList.take(6).toList();
        debugPrint("imageMaxList数量: ${imageMaxList.length}, 原始imageList数量: ${imageList.length}");
        

        Map qcImageVoGroupMap = productDetail["qcImageVoGroupMap"] ?? {};

        // 获取Map的所有键
        Iterable<dynamic> keys = qcImageVoGroupMap.keys;

        // 打印所有键
        debugPrint("qcImageVoGroupMap keys: $keys");

        // 如果需要将键转换为List
        List<dynamic> keysList = keys.toList();
        debugPrint("qcImageVoGroupMap keysList: $keysList");

        imageMinList.clear();
        if(keysList.isNotEmpty){
          // 遍历所有keys，收集图片，最多12张
          for(String key in keysList) {
            if(imageMinList.length >= 12) break; // 已达到12张，停止收集
            
            List dataList = qcImageVoGroupMap[key]??[];
            for(Map data in dataList){
              if(imageMinList.length >= 12) break; // 已达到12张，停止收集
              
              String url = data["imageUrl"];
              imageMinList.add(showPictureUrl(url));
            }
          }
          debugPrint("收集到的图片数量: ${imageMinList.length}");
        }
        if(mainUrl != ""){
          homeBloc.add(GetSearchSimilarityImageEvent(context,mainUrl));
        }
        homeBloc.add(postProductIsCollectedEvent(context, widget.itemNo));

        RecordBrowseManager.addRecordBrowse(productDetail);
        return true;

      }
      if(state is GetJOYProductDetailEventFailure){
        error_alc = state.errMsg;
        isNetError_alc = true;
      }
      if(state is GetSearchSimilarityImageEventSuccess){
        debugPrint("=== 商品详情页接收相似商品数据 ===");
        debugPrint("state.data 类型: ${state.data.runtimeType}");
        debugPrint("state.data 内容: ${state.data}");
        
        SimilarityList.clear();
        
        try {
          // 🔥 类型检查和转换
          if (state.data is ProductListModel) {
            ProductListModel modellist = state.data as ProductListModel;
            // 🔥 最多只添加6个相似商品
            int maxCount = modellist.productModels.length > 6 ? 6 : modellist.productModels.length;
            SimilarityList.addAll(modellist.productModels.take(maxCount));
            debugPrint("✅ 成功添加${maxCount}个相似商品（总共${modellist.productModels.length}个）");
          } else if (state.data is List) {
            // 如果是List类型，直接添加，最多6个
            List dataList = state.data as List;
            int maxCount = dataList.length > 6 ? 6 : dataList.length;
            SimilarityList.addAll(dataList.take(maxCount));
            debugPrint("⚠️ 收到List类型数据，添加了${maxCount}个（总共${dataList.length}个）");
          } else {
            debugPrint("❌ 未知的数据类型: ${state.data.runtimeType}");
          }
          
          debugPrint("相似商品列表数量: ${SimilarityList.length}");
          if (SimilarityList.isNotEmpty) {
            debugPrint("=== 前3个相似商品 ===");
            for (int i = 0; i < SimilarityList.length && i < 3; i++) {
              var product = SimilarityList[i];
              debugPrint("相似商品${i + 1}: ${product.title} - ${product.price}");
            }
          } else {
            debugPrint("⚠️ 相似商品列表为空");
          }
          
        } catch (e, stackTrace) {
          debugPrint("❌ 处理相似商品数据出错: $e");
          debugPrint("错误堆栈: $stackTrace");
        }
        
        return true;
      }

      if(state is GetSearchSimilarityImageEventFailure){
        debugPrint("=== 获取相似商品失败 ===");
        debugPrint("失败原因: ${state.errMsg}");
        SimilarityList.clear();
        return true;
      }

      // if(state is GetSearchImageEventSuccess){
      //   SimilarityList.clear();
      //   ProductListModel modellist = state.data;
      //   SimilarityList.addAll(modellist.productModels);
      //
      //     debugPrint("相似图片的格式 = ${SimilarityList}");
      //   return true;
      // }
      //
      // if(state is GetSearchImageEventFailure){
      //
      // }

      if(state is postProductIsCollectedEventSuccess){
        print("postProductIsCollectedEventSuccess = ${state.data}");
        Map collectionMap = state.data;
        isCollection = collectionMap["type"]??0;
        return true;

      }
      if(state is postProductIsCollectedEventFailure){
        print("postProductIsCollectedEventFailure = ${state.errMsg}");
      }


      if(state is postAddProductCollectedEventSuccess){
        print("postAddProductCollectedEventSuccess = ${state.data}");
        isCollection = 1;
        // 收藏成功
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Row(
              children: [
                Icon(
                  Icons.favorite,
                  color: Colors.white,
                  size: 20,
                ),
                SizedBox(width: 8),
                Text(
                  'Added to favorites',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ],
            ),
            backgroundColor: Colors.green,
            duration: Duration(seconds: 2),
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(8),
            ),
            margin: EdgeInsets.all(16),
          ),
        );
        return true;

      }
      if(state is postAddProductCollectedEventFailure){
        // 收藏失败
        print("postProductIsCollectedEventFailure = ${state.errMsg}");
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Row(
              children: [
                Icon(
                  Icons.error_outline,
                  color: Colors.white,
                  size: 20,
                ),
                SizedBox(width: 8),
                Text(
                  'Failed to add to favorites: ${state.errMsg ?? "Unknown error"}',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ],
            ),
            backgroundColor: Colors.red,
            duration: Duration(seconds: 3),
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(8),
            ),
            margin: EdgeInsets.all(16),
          ),
        );
      }

      return true;

    });
  }

  String showPictureUrl(String url){

    String main = "";
    if(url.contains("http")){
      main =  url;
    }else{
      main = "${joyProductPicUrl}${url}";
    }

    String mainUrl = Uri.encodeFull(main);
    return mainUrl;
  }

  Widget detailMain(){
    return Scaffold(
      backgroundColor: Colors.white,
      body: Stack(
        children: [
          CustomScrollView(
            slivers: [
              // 图片轮播区域
              SliverToBoxAdapter(
                child: showImageList(),
              ),
          
          // 商品信息区域
          SliverToBoxAdapter(
            child: Container(
              color: Colors.white,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 商品标题和收藏按钮
                  _buildProductHeader(),
                  
                  // 价格和折扣信息
                  _buildPriceSection(),
                  
                  // 倒计时

                  // 操作按钮
                  _buildActionButtons(),
                  
                  // 卖家信息
                  _buildSellerInfo(),
                  
                  // 商品详情图片
                  _buildProductDetailImages(),
                  
                  // 图片展示轮播
                  _buildImageCarousel(),
                  // 商品推荐
                  _buildProductRecommendation(),
                   SizedBox(height: MediaQuery.of(context).padding.bottom + 20.h), // 底部安全距离
                ],
              ),
            ),
          ),
        ],
        ),
          // 返回按钮
          Positioned(
            top: 50.h,
            left: 20.w,
            child: _buildBackButton(),
          ),
        ],
      ),
    );
  }


  // 构建商品推荐区域
  Widget _buildProductRecommendation() {
    // 只有当 SimilarityList 不为空时才显示推荐区域
    if (SimilarityList.isEmpty) {
      return SizedBox.shrink();
    }
    
    // 计算需要的行数
    int itemCount = SimilarityList.length > 6 ? 6 : SimilarityList.length;
    int crossAxisCount = 2;
    int rowCount = (itemCount / crossAxisCount).ceil();
    
    // 计算自适应高度
    double itemHeight = 225.h; // 每个商品卡片的高度
    double spacing = 12.h; // 行间距
    double totalHeight = (itemHeight * rowCount) + (spacing * (rowCount - 1));
    
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 12.w, vertical: 12.h),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            "Similar Products",
            style: TextStyle(
              fontSize: 16.sp,
              fontWeight: FontWeight.w600,
              color: Colors.black87,
            ),
          ),
          SizedBox(height: 6.h),
          Container(
            height: totalHeight, // 使用计算出的自适应高度
            child: _buildProductList(),
          ),
        ],
      ),
    );
  }

  Widget _buildProductList() {
    return GridView.builder(
      padding: EdgeInsets.all(2), // 移除内边距，由外层容器控制
      physics: NeverScrollableScrollPhysics(), // 禁用滚动，由外层 CustomScrollView 控制
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        childAspectRatio: 0.72,
        crossAxisSpacing: 16.w,
        mainAxisSpacing: 16.h,
      ),
      itemCount: SimilarityList.length > 6 ? 6 : SimilarityList.length,
       itemBuilder: (context, index) {
         ProductModel? productmodel = SimilarityList[index];
         return JoyProductCardWidget(
           productModel: productmodel,
           onTap: () {
             // 跳转到商品详情页
             if (productmodel != null) {
               Navigator.push(
                 context,
                 MaterialPageRoute(
                   builder: (context) => JoyProductDetailPage(
                     itemNo: productmodel.channelItemNo ?? "",
                     channel: productmodel.channel ?? "",
                     productName: productmodel.title ?? "",
                   ),
                 ),
               );
             }
           },
           onFavorite: () async {
             // 检查登录状态
             bool isLoggedIn = await _checkLoginStatus();
             if (!isLoggedIn) {
               // 未登录，显示登录提示
               _showLoginRequiredDialog();
               return;
             }
             
             // 已登录，执行收藏逻辑
             // TODO: 实现收藏功能
           },
         );
       },
    );
  }

  Widget showImageList(){
    // 确保图片列表不为空且包含有效数据
    List<String> validImages = [];
    if (imageList.isNotEmpty) {
      for (var item in imageList) {
        if (item != null && item.toString().isNotEmpty) {
          validImages.add(item.toString());
        }
      }
    }
    
    // 如果没有图片数据，显示占位符
    if (validImages.isEmpty) {
      return Container(
        height: 400,
        decoration: BoxDecoration(
          color: Colors.grey[100],
          borderRadius: BorderRadius.circular(12),
        ),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                Icons.image_not_supported,
                size: 50,
                color: Colors.grey[400],
              ),
              SizedBox(height: 8),
              Text(
                'No images available',
                style: TextStyle(
                  color: Colors.grey[600],
                  fontSize: 16,
                ),
              ),
            ],
          ),
        ),
      );
    }
    
    return Container(
      height: 400,
      child: ImageCarouselWidget(
        images: validImages,  // 使用处理后的有效图片数组
        autoPlay: validImages.length > 1,  // 只有多张图片时才自动播放
        autoPlayInterval: Duration(seconds: 3),  // 播放间隔
        height: 400,  // 主图高度
        previewHeight: 80,  // 预览图高度
      ),
    );
  }

  // 复制文本到剪切板
  Future<void> _copyToClipboard(String textStr) async {
    await Clipboard.setData(ClipboardData(text: textStr));
    await JoyActionService.FindlogCopyLink(textStr,widget.itemNo);

  }

    void joyShowdiasertlog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text(' 🔗 Link copied to clipboard'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text("We recommend opening it on your computer for smoother checkout."),
            const SizedBox(height: 8),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('OK'),
          ),
        ],
      ),
    );
  }

  void joyShowdialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: Colors.transparent,
        contentPadding: EdgeInsets.zero,
        content: Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(16.r),
            color: Colors.white,
            // gradient: LinearGradient(
            //   begin: Alignment.topLeft,
            //   end: Alignment.bottomRight,
            //   colors: [
            //     Color(0xFFFFF8F5), // 浅橙色
            //     Color(0xFFFFF0E6), // 更浅的橙色
            //     Color(0xFFFFE8D6), // 淡橙色
            //   ],
            //   stops: [0.0, 0.5, 1.0],
            // ),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.1),
                blurRadius: 20,
                offset: Offset(0, 10),
              ),
            ],
          ),
          padding: EdgeInsets.all(24.w),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 自定义图标
              Container(
                width: 80.w,
                height: 80.w,
                // decoration: BoxDecoration(
                //   borderRadius: BorderRadius.circular(12.r),
                //   color: Colors.white.withOpacity(0.8),
                //   boxShadow: [
                //     BoxShadow(
                //       color: Colors.black.withOpacity(0.05),
                //       blurRadius: 10,
                //       offset: Offset(0, 5),
                //     ),
                //   ],
                // ),
                child: Center(
                  child: Image.asset(
                    'images/copy_link.png',
                    width: 80.w,
                    height: 80.w,
                    fit: BoxFit.contain,
                  ),
                ),
              ),
              SizedBox(height: 20.h),
              // 标题
              Text(
                'Link copied to clipboard',
                style: TextStyle(
                  fontSize: 18.sp,
                  fontWeight: FontWeight.w600,
                  color: Colors.black87,
                ),
                textAlign: TextAlign.center,
              ),
              SizedBox(height: 12.h),
              // 描述文字
              Text(
                "We recommend opening it on your computer for smoother checkout.",
                style: TextStyle(
                  fontSize: 14.sp,
                  color: Colors.grey[600],
                  height: 1.4,
                ),
                textAlign: TextAlign.center,
              ),
              SizedBox(height: 24.h),
              // OK 按钮
              SizedBox(
                width: double.infinity,
                height: 35.h,
                child: ElevatedButton(
                  onPressed: () => Navigator.of(context).pop(),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: AppColors.primary,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(24.h),
                    ),
                    elevation: 0,
                  ),
                  child: Text(
                    'OK',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 16.sp,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget showImageLittlePicture(String url){
    return CachedNetworkImage(
      fit: BoxFit.cover,
      imageUrl: url,
      cacheManager: JoyCacheManager.instance,
      placeholder: (context,imageUrl){
        return Container(
          color: Colors.grey[200],
          child: Center(
            child: SizedBox(
              width: 20,
              height: 20,
              child: CircularProgressIndicator(
                valueColor: AlwaysStoppedAnimation<Color>(Colors.orange),
                strokeWidth: 2,
              ),
            ),
          ),
        );
      },
      errorWidget: (context,imageUrl,error){
        return Container(
          color: Colors.grey[100],
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(
                  Icons.broken_image_outlined,
                  size: 24,
                  color: Colors.grey[400],
                ),
                SizedBox(height: 4),
                Text(
                  "Loading failed",
                  style: TextStyle(
                    color: Colors.grey[500],
                    fontSize: 10,
                  ),
                ),
              ],
            ),
          ),
        );
      },
      fadeInDuration: Duration(milliseconds: 200),
      fadeOutDuration: Duration(milliseconds: 100),
    );
  }

  // 构建商品标题和收藏按钮
  Widget _buildProductHeader() {
    return Container(
      padding: EdgeInsets.only(top: 16.w,left: 20.w,right: 20.w),
      child: Row(
        children: [
          Expanded(
            child: Text(
              "${widget.productName}",
              style: TextStyle(
                fontSize: 16.sp,
                fontWeight: FontWeight.w400,
                color: Colors.black87,
                height: 1.3,
              ),
            ),
          ),
          GestureDetector(
            onTap: () async {
              // 检查登录状态
              bool isLoggedIn = await _checkLoginStatus();
              if (!isLoggedIn) {
                // 未登录，显示登录提示
                _showLoginRequiredDialog();
                return;
              }
              
              // 已登录，执行收藏逻辑
              if(isCollection == 0){
                homeBloc.add(postAddProductCollectedEvent(context, widget.itemNo));
              }
            },
            child: Container(
              padding: EdgeInsets.all(8),
              // decoration: BoxDecoration(
              //   color: Colors.white,
              //   shape: BoxShape.circle,
              //   boxShadow: [
              //     BoxShadow(
              //       color: Colors.black.withOpacity(0.1),
              //       blurRadius: 4,
              //       offset: Offset(0, 2),
              //     ),
              //   ],
              // ),
              child: Icon(
                (isCollection == 1)? Icons.star:Icons.star_border_outlined,
                color: AppColors.backHomeYellowGround,
                size: 24,
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 构建价格和折扣信息
  Widget _buildPriceSection() {
    double discountPercent = discountRate * 100;
    String displayPriceStr = "";
    String originalPriceStr = "";

    if (statusRate == 1) {
      // 活动期间：显示折扣价，原价作为对比
      displayPriceStr = price;
      originalPriceStr = discountPrice;
    } else {
      // 非活动期间：优先显示原价，如果原价为null或0则显示折扣价
      if (discountPrice.isNotEmpty && discountPrice != "0.0" && discountPrice != "0") {
        displayPriceStr = discountPrice; // 显示原价
        originalPriceStr = ""; // 不显示对比价格
      } else {
        displayPriceStr = price; // 原价无效时显示折扣价
        originalPriceStr = ""; // 不显示对比价格
      }
    }
    
    return Container(
      margin: EdgeInsets.only(left: 12.w,right: 12.w,bottom: 8.w,top: 8.w),
      padding: EdgeInsets.only(left: 12,top: 12,bottom: 12),
      decoration: BoxDecoration(
        color: AppColors.primary,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: Colors.transparent,
          width: 1,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 价格信息
          Row(
            children: [
              Text(
                "${CurrencyManager.instance.currentCurrency.symbol}${displayPriceStr}",
                style: TextStyle(
                  fontSize: 28,
                  fontWeight: FontWeight.bold,
                  color: AppColors.backHomeYellowGround,
                ),
              ),
              SizedBox(width: 8),
              if (originalPriceStr.isNotEmpty)
                Text(
                  "/${CurrencyManager.instance.currentCurrency.symbol}${originalPriceStr}",
                  style: TextStyle(
                    fontSize: 16,
                    color: AppColors.backHomeYellowGround.withOpacity(0.6),
                    decoration: TextDecoration.lineThrough,
                  ),
                ),
            ],
          ),
          SizedBox(height: 8),

          Row(
            children: [
              // 只在活动期间显示折扣标签
              if (statusRate == 1)
                Container(
                  padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                  decoration: BoxDecoration(
                    color: AppColors.backHomeYellowGround,
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Text(
                    "${discountPercent}% OFF",
                    style: TextStyle(
                      color: AppColors.primary,
                      fontSize: 12,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ),

              // 只在活动期间显示倒计时
              if (statusRate == 1)
                _buildCountdownSection(),
            ],
          ),
          // 折扣标签
        ],
      ),
    );
  }

  // 构建倒计时区域
  Widget _buildCountdownSection() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 8, vertical: 8),
      child: Row(
        children: [
          Text(
            "Only Time:",
            style: TextStyle(
              fontSize: 14,
              color: Colors.white,
              fontWeight: FontWeight.w500,
            ),
          ),
          SizedBox(width: 08),
          _buildCountdownTimer(),
        ],
      ),
    );
  }

  // 构建倒计时器
  Widget _buildCountdownTimer() {
    return Row(
      children: [
        _buildTimeUnit("H", _remainingHours.toString().padLeft(2, '0')),
        SizedBox(width: 8),
        _buildTimeUnit("M", _remainingMinutes.toString().padLeft(2, '0')),
        SizedBox(width: 8),
        _buildTimeUnit("S", _remainingSeconds.toString().padLeft(2, '0')),
      ],
    );
  }

  // 构建时间单位
  Widget _buildTimeUnit(String label, String value) {
    return Row(
      children: [
        Text(
          label,
          style: TextStyle(
            fontSize: 12,
            color: Colors.white,
            fontWeight: FontWeight.w500,
          ),
        ),
        SizedBox(width: 4),
        Container(
          padding: EdgeInsets.all(5),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(4),

          ),
          child: Center(
            child: Text(
              value,
              style: TextStyle(
                fontSize: 12,
                fontWeight: FontWeight.bold,
                color: AppColors.primary,
              ),
            ),
          ),
        ),
      ],
    );
  }

  // 构建操作按钮
  Widget _buildActionButtons() {
    // 🔥 添加对计数器的引用，确保UI能响应AppTheme变化
    final _ = _appThemeUpdateCounter;
    
    final bool isSpecialDate = _isInSpecialDateRange();
  
    final bool shouldShowTwoButtons = AppTheme.UserAppTheme == '0';
    
 
    final bool shouldDisplayTwoButtons = shouldShowTwoButtons || (!isSpecialDate && !shouldShowTwoButtons);
    
    debugPrint("📊 按钮构建 - UserAppTheme: ${AppTheme.UserAppTheme}, isSpecialDate: $isSpecialDate, shouldDisplayTwoButtons: $shouldDisplayTwoButtons");
    
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 20, vertical: 16),
      child: Row(
        children: [
          // Copy Link 按钮
          Expanded(
            flex: shouldDisplayTwoButtons ? 2 : 1,
            child: Container(
              height: 48,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(8),
                border: Border.all(
                  color: AppColors.primary,
                  width: 1,
                ),
              ),
              child: ElevatedButton(
                onPressed: () {
                  _copyToClipboard(productLink);
                  joyShowdialog(context);
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.transparent,
                  shadowColor: Colors.transparent,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
                ),
                child: Text(
                  'Copy link',
                  style: TextStyle(
                    color: AppColors.primary,
                    fontSize: 16,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
            ),
          ),
          // 🔥 根据最终判断结果决定是否显示Buy Now按钮
          if (shouldDisplayTwoButtons) ...[
            SizedBox(width: 10),
            // Buy Now 按钮
            Expanded(
              flex: 2,
              child: Container(
                height: 48,
                decoration: BoxDecoration(
                  color: AppColors.primary,
                  borderRadius: BorderRadius.circular(8),
                ),
                child: ElevatedButton(
                  onPressed: () {

                    LitDialogUtil.showLitSheet(
                      context,
                      LitPlatformVoLWidget(
                        platformList: _convertFindVoList(platformList),
                        onClose: () {
                          // 关闭弹窗
                        },
                        onPlatformSelected: (platform) {
                          // 处理平台选择事件
                          _handleFindClickPlatformTap(platform.name ?? "Unknown", platform.productLink ?? "");

                        },
                        onPlatformCopySelected: (platform) async {
                          // 处理复制链接事件
                          // await _copyToClipboard(platform.productLink ?? "");
                        },
                      ),
                      scrollControlled: true,
                    );

                  },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.transparent,
                    shadowColor: Colors.transparent,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  child: Text(
                    'Buy Now',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 16,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ),
              ),
            ),
          ],
          // SizedBox(width: 12),
          // 分享按钮
          // GestureDetector(
          //   onTap: () {
          //     // TODO: 实现分享功能
          //   },
          //   child: Container(
          //     width: 48,
          //     height: 48,
          //     decoration: BoxDecoration(
          //       color: Colors.white,
          //       borderRadius: BorderRadius.circular(8),
          //       border: Border.all(
          //         color: Color(0xFFFF6B35),
          //         width: 1,
          //       ),
          //     ),
          //     child: Icon(
          //       Icons.share,
          //       color: Color(0xFFFF6B35),
          //       size: 20,
          //     ),
          //   ),
          // ),
        ],
      ),
    );
  }

  // 处理平台点击事件
  void _handleFindClickPlatformTap(String platformName, String link) {

    // if (platformName.contains("iTao")) {
    //
    //   NavigatorUtil().to(WebViewPage(initialUrl: link));
    //
    // } else {

    JoyActionService.LitopenInSystemAppBrowser(link);

    // }
    JoyActionService.FindlogOpenLink(link,widget.itemNo);
  }

  //
  List<PlatformVoList> _convertFindVoList(List<dynamic> platformList) {
    return platformList.map((platform) {
      if (platform is Map<String, dynamic>) {
        return PlatformVoList.fromJson(platform);
      }
      return PlatformVoList(
        name: "Unknown",
        nameEn: "Unknown",
        productLink: "",
        recommendFlag: 0,
      );
    }).toList();
  }

  // 构建卖家信息
  Widget _buildSellerInfo() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 12, vertical: 12),
      padding: EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Color(0xFFF6F6F6),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Row(
        children: [
          SizedBox(width: 12),
          // 卖家名称
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  "TRENDY HUB",
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: Colors.black87,
                  ),
                ),
                SizedBox(height: 4),
                Row(
                  children: [
                    Container(
                      padding: EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                      decoration: BoxDecoration(
                        color: Colors.amber,
                        borderRadius: BorderRadius.circular(4),
                      ),
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Icon(
                            Icons.verified,
                            color: Colors.white,
                            size: 12,
                          ),
                          SizedBox(width: 2),
                          Text(
                            "Trusted Seller",
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 10,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 构建商品详情图片
  Widget _buildProductDetailImages() {
    if (imageMaxList.isEmpty) {
      return SizedBox.shrink();
    }
    
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 12.w, vertical: 0.h),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            "Product Details",
            style: TextStyle(
              fontSize: 18.sp,
              fontWeight: FontWeight.w600,
              color: Colors.black87,
            ),
          ),
          ListView.builder(
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(),
            itemCount: imageMaxList.length,
            itemBuilder: (context, index) {
              String url = imageMaxList[index].toString();
              return Container(
                margin: EdgeInsets.only(bottom: 12.h),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(12.r),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.1),
                      blurRadius: 8,
                      offset: Offset(0, 2),
                    ),
                  ],
                ),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(12.r),
                  child: _buildDetailImage(url, index),
                ),
              );
            },
          ),
        ],
      ),
    );
  }

  // 构建详情图片
  Widget _buildDetailImage(String imageUrl, int index) {
    return GestureDetector(
      onTap: () {
        // TODO: 实现图片点击放大功能
      },
      child: CachedNetworkImage(
        imageUrl: imageUrl,
        fit: BoxFit.cover,
        width: double.infinity,
        cacheManager: JoyCacheManager.instance,
        placeholder: (context, url) => Container(
          height: 200.h,
          color: Colors.grey[200],
          child: Center(
            child: SizedBox(
              width: 30.w,
              height: 30.w,
              child: CircularProgressIndicator(
                valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFFD6C34)),
                strokeWidth: 3,
              ),
            ),
          ),
        ),
        errorWidget: (context, url, error) => Container(
          height: 200.h,
          color: Colors.grey[100],
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(
                  Icons.broken_image_outlined,
                  size: 40.sp,
                  color: Colors.grey[400],
                ),
                SizedBox(height: 8.h),
                Text(
                  "Image loading failed",
                  style: TextStyle(
                    color: Colors.grey[500],
                    fontSize: 14.sp,
                  ),
                ),
              ],
            ),
          ),
        ),
        fadeInDuration: Duration(milliseconds: 300),
        fadeOutDuration: Duration(milliseconds: 100),
      ),
    );
  }

  // 构建图片轮播组件
  Widget _buildImageCarousel() {
    if (imageMinList.isEmpty) {
      return SizedBox.shrink();
    }
    
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 20.w, vertical: 16.h),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            "QC photos（${imageMinList.length}）",
            style: TextStyle(
              fontSize: 18.sp,
              fontWeight: FontWeight.w600,
              color: Colors.black87,
            ),
          ),
          SizedBox(height: 12.h),
          Container(
            height: 300.h,
            child: Stack(
              children: [
                // 使用纯 GridView 实现左右滑动
                GridView.builder(
                  controller: _carouselPageController,
                  scrollDirection: Axis.horizontal, // 水平滚动
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 2, // 2行
                    childAspectRatio: 0.7, // 调整宽高比以适应水平滚动
                    crossAxisSpacing: 8.w,
                    mainAxisSpacing: 8.h,
                  ),
                  itemCount: imageMinList.length,
                  itemBuilder: (context, index) {
                    return _buildCarouselImage(
                      imageMinList[index].toString(),
                      index,
                    );
                  },
                ),
                
                // 左侧导航箭头
                // Positioned(
                //   left: 0,
                //   top: 0,
                //   bottom: 0,
                //   child: Center(
                //     child: GestureDetector(
                //       onTap: () {
                //         if (_carouselPageController.hasClients) {
                //           _carouselPageController.animateTo(
                //             (_carouselPageController.offset - 200).clamp(0.0, _carouselPageController.position.maxScrollExtent),
                //             duration: Duration(milliseconds: 300),
                //             curve: Curves.easeInOut,
                //           );
                //         }
                //       },
                //       child: Container(
                //         width: 32.w,
                //         height: 32.w,
                //         decoration: BoxDecoration(
                //           color: Colors.black.withOpacity(0.3),
                //           shape: BoxShape.circle,
                //         ),
                //         child: Icon(
                //           Icons.chevron_left,
                //           color: Colors.white,
                //           size: 20.sp,
                //         ),
                //       ),
                //     ),
                //   ),
                // ),
                
                // 右侧导航箭头
                // Positioned(
                //   right: 0,
                //   top: 0,
                //   bottom: 0,
                //   child: Center(
                //     child: GestureDetector(
                //       onTap: () {
                //         if (_carouselPageController.hasClients) {
                //           _carouselPageController.animateTo(
                //             (_carouselPageController.offset + 200).clamp(0.0, _carouselPageController.position.maxScrollExtent),
                //             duration: Duration(milliseconds: 300),
                //             curve: Curves.easeInOut,
                //           );
                //         }
                //       },
                //       child: Container(
                //         width: 32.w,
                //         height: 32.w,
                //         decoration: BoxDecoration(
                //           color: Colors.black.withOpacity(0.3),
                //           shape: BoxShape.circle,
                //         ),
                //         child: Icon(
                //           Icons.chevron_right,
                //           color: Colors.white,
                //           size: 20.sp,
                //         ),
                //       ),
                //     ),
                //   ),
                // ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 构建轮播图片项
  Widget _buildCarouselImage(String imageUrl, int index) {
    return GestureDetector(
      onTap: () {
        // TODO: 实现图片点击放大功能
      },
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8.r),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.1),
              blurRadius: 4,
              offset: Offset(0, 2),
            ),
          ],
        ),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(8.r),
          child: CachedNetworkImage(
            imageUrl: imageUrl,
            fit: BoxFit.cover,
            cacheManager: JoyCacheManager.instance,
            placeholder: (context, url) => Container(
              color: Colors.grey[200],
              child: Center(
                child: SizedBox(
                  width: 20.w,
                  height: 20.w,
                  child: CircularProgressIndicator(
                    valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFFD6C34)),
                    strokeWidth: 2,
                  ),
                ),
              ),
            ),
            errorWidget: (context, url, error) => Container(
              color: Colors.grey[100],
              child: Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(
                      Icons.broken_image_outlined,
                      size: 24.sp,
                      color: Colors.grey[400],
                    ),
                    SizedBox(height: 4.h),
                    Text(
                      "Loading failed",
                      style: TextStyle(
                        color: Colors.grey[500],
                        fontSize: 10.sp,
                      ),
                    ),
                  ],
                ),
              ),
            ),
            fadeInDuration: Duration(milliseconds: 200),
            fadeOutDuration: Duration(milliseconds: 100),
          ),
        ),
      ),
    );
  }

  Widget _buildActionButton(IconData icon, VoidCallback onTap) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: Colors.white.withOpacity(0.9),
          shape: BoxShape.circle,
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.1),
              blurRadius: 8,
              offset: Offset(0, 2),
            ),
          ],
        ),
        child: Icon(
          icon,
          color: Colors.black,
          size: 20,
        ),
      ),
    );
  }

  // 构建返回按钮
  Widget _buildBackButton() {
    return GestureDetector(
      onTap: () {
        Navigator.of(context).pop();
      },
      child: Container(
        padding: EdgeInsets.only(left: 5.w),
        width: 40.w,
        height: 40.w,
        decoration: BoxDecoration(
          color: Colors.grey[600],
          borderRadius: BorderRadius.circular(8.r),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.1),
              blurRadius: 4,
              offset: Offset(0, 2),
            ),
          ],
        ),
        child: Center(
          child: Icon(
            Icons.arrow_back_ios,
            color: Colors.white,
            size: 20.w,
          ),
        ),
      ),
    );
  }
}